const inspirecloud = require('@byteinspire/api')
const dbUtils = require('../utils/dbUtils')


// 搜索用户
const findUsers = async function(target, count) {
  const Users = inspirecloud.db.table('users');
  const tel = new RegExp(`^${target}`, `ig`)
  const limit = count || 1
  const userList = await Users.where({username: tel}).or({nickname: tel}).limit(limit).find();
  let userInfoList = []
  if (userList && userList.length) {
    for (const user of userList) {
      userInfoList.push({
        userId: user._id,
        userName: user.username,
        nickName: user.nickname,
        avatar: user.avatar
      })
    }
  }
  return userInfoList
}


// 搜索视频
const findVideos = async function(target, count) {
  const Vidoes = inspirecloud.db.table('videos');
  const title = new RegExp(`^${target}`, `ig`)
  const desc = new RegExp(`${target}`, `g`)
  const limit = count || 5
  const videoList = await Vidoes.where({title: title}).or({desc: desc}).sort({updatedAt: -1}).limit(limit).find();
  for (const video of videoList) {
    const authorInfo = await dbUtils.findUserByUserId(video.author)
    video.authorNickName = authorInfo.nickname
    video.authorUserName = authorInfo.username
    video.authorAvatar = authorInfo.avatar
  }
  return videoList
}



module.exports = {
  findUsers,
  findVideos
}